package coml.jiyun.hp.ershi.fragment;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import coml.jiyun.hp.ershi.DbUtil;
import coml.jiyun.hp.ershi.R;
import coml.jiyun.hp.ershi.adapter.RlvCollectAdapter;
import coml.jiyun.hp.ershi.bean.WanBeanTwo;
import coml.jiyun.hp.ershi.db.WanBeanTwoDao;

import static coml.jiyun.hp.ershi.BaseApp.getInstance;

/**
 * A simple {@link Fragment} subclass.
 */
public class CollectFragment extends Fragment {

    private RecyclerView mRlv;
    private ArrayList<WanBeanTwo> wanBeanTwos;
    private RlvCollectAdapter rlvCollectAdapter;

    public CollectFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_collect, container, false);
        initView(inflate);
        initQuery();
        return inflate;
    }

    private void initQuery() {
        List<WanBeanTwo> query = DbUtil.dbUtil().query();
        wanBeanTwos.addAll(query);
        rlvCollectAdapter.setWanBeanTwos(wanBeanTwos);
        rlvCollectAdapter.notifyDataSetChanged();
    }

    private void initView(View inflate) {
        mRlv = inflate.findViewById(R.id.collect_rlv);

        wanBeanTwos = new ArrayList<>();
        rlvCollectAdapter = new RlvCollectAdapter(getActivity(), wanBeanTwos);
        mRlv.setAdapter(rlvCollectAdapter);
        mRlv.setLayoutManager(new LinearLayoutManager(getActivity()));

        rlvCollectAdapter.setOnItemClick(new RlvCollectAdapter.onItemClick() {
            @Override
            public void cx(int i) {
            }
        });
    }

    @Override
         public void setUserVisibleHint(boolean isVisibleToUser) {
             super.setUserVisibleHint(isVisibleToUser);
             if (getUserVisibleHint()){
                 initData();
             }else {
                 if (wanBeanTwos != null && wanBeanTwos.size()>0){
                     wanBeanTwos.clear();
                 }
             }
         }

     private void initData() {
         WanBeanTwoDao beanDao = getInstance().getDaoSession().getWanBeanTwoDao();
                 List<WanBeanTwo> all = beanDao.loadAll();
                 wanBeanTwos.addAll(all);
                  rlvCollectAdapter.notifyDataSetChanged();
    }
}